﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using AvalonDock;
using System.Data.Objects.DataClasses;
using ModeloGaleriaNET;
using CADs;
using SeguridadGaleria;

namespace GaleriaNET
{
    /// <summary>
    /// Lógica de interacción para ucSubastas.xaml
    /// </summary>
    public partial class ucSubastas : UserControl
    {
        private string[] permisos = new string[] { TiposRoles.VISUALIZAR_SUBASTA,
             TiposRoles.CANCELAR_SUBASTA, TiposRoles.MODIFICAR_DATOS_SUBASTA, 
         TiposRoles.CREAR_SUBASTA, 
        TiposRoles.FINALIZAR_SUBASTA,
        TiposRoles.PUJAR, TiposRoles.VER_LISTADO_PUJAS};
        private readonly int pageSize = int.Parse(CADs.Properties.Resources.PageSize);
        private readonly string title = "Gestión de subastas";
        private BackgroundWorker worker, workerPermisos;
        private int pagenum;
        private List<Subasta> subastas;
        private bool success;
        private int numSubastas;
        private SubastaCAD subastaCAD;
        private bool loaded;
        private Dictionary<string, bool> permisosDatos;

        public ucSubastas()
        {
            InitializeComponent();
            loaded = false;
            #region Definición del BackgroundWorker
            worker = new BackgroundWorker();
            worker.DoWork += worker_DoWork;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
            workerPermisos = new BackgroundWorker();
            workerPermisos.DoWork += workerPermisos_DoWork;
            workerPermisos.RunWorkerCompleted += workerPermisos_RunWorkerCompleted;
            #endregion
        }

        public string Title
        {
            get { return title; }
        }

        public SubastaCAD SubastaCAD
        {
            get { return subastaCAD; }
        }

        private void workerPermisos_DoWork(object sender, DoWorkEventArgs e)
        {
            string usuario;
            bool? value;

            permisosDatos = new Dictionary<string, bool>();
            usuario = Convert.ToString(Utilities.FindUsuarioData(typeof(UserWindow), this, "Name"));

            foreach (string s in permisos)
            {
                value = ManejadorRoles.Instance.CanUse(s, usuario);
                if (value != null)
                    permisosDatos.Add(s, value.Value);
            }
        }

        private void workerPermisos_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            bool value, value2, value3;
            IntPtr b;
            BitmapSource bs;

            if (!(permisosDatos != null && permisosDatos.Count == permisos.Length))
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("No se han podido obtener todos los permisos", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                btNuevo.IsEnabled = false;
                b = Properties.Resources.Agregar_gris_24.GetHbitmap();
                bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(b, IntPtr.Zero, Int32Rect.Empty,
                  System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                this.imgBtNuevo.Source = bs;
                dgSubastas.MouseDoubleClick -= dgSubastas_MouseDoubleClick;
            }
            else
            {
                permisosDatos.TryGetValue(TiposRoles.VISUALIZAR_SUBASTA, out value2);

                if (!value2)
                {
                    btNuevo.IsEnabled = false;
                    b = Properties.Resources.Agregar_gris_24.GetHbitmap();
                    bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(b, IntPtr.Zero, Int32Rect.Empty,
                      System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                    this.imgBtNuevo.Source = bs;
                    dgSubastas.MouseDoubleClick -= dgSubastas_MouseDoubleClick;
                }
                else
                {
                    permisosDatos.TryGetValue(TiposRoles.CREAR_SUBASTA, out value);
                    
                    if (!value) // No se puede publicar una subasta
                    {
                        btNuevo.IsEnabled = false;
                        b = Properties.Resources.Agregar_gris_24.GetHbitmap();
                        bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(b, IntPtr.Zero, Int32Rect.Empty,
                          System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                        this.imgBtNuevo.Source = bs;
                    }

                    permisosDatos.TryGetValue(TiposRoles.VER_LISTADO_PUJAS, out value);
                    value3 = value;

                    permisosDatos.TryGetValue(TiposRoles.MODIFICAR_DATOS_SUBASTA, out value);
                   
                    value3 = value3 || value;

                    permisosDatos.TryGetValue(TiposRoles.CANCELAR_SUBASTA, out value);
                   
                    value3 = value3 || value;

                    permisosDatos.TryGetValue(TiposRoles.FINALIZAR_SUBASTA, out value);
                   
                    value3 = value3 || value;

                    permisosDatos.TryGetValue(TiposRoles.PUJAR, out value);
                    value3 = value3 || (value && value2);

                    if (!value3)
                        dgSubastas.MouseDoubleClick -= dgSubastas_MouseDoubleClick;
                }
            }
        }

        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            while (workerPermisos.IsBusy)
            { }

            try
            {
                subastas = subastaCAD.GetSubastasPaginated(pagenum);
                numSubastas = subastaCAD.GetSubastasCount();
                success = true;
            }
            catch (Exception)
            {
                try
                {
                    System.Threading.Thread.Sleep(1500);
                    subastas = subastaCAD.GetSubastasPaginated(pagenum);
                    numSubastas = subastaCAD.GetSubastasCount();
                    success = true;
                }
                catch (Exception)
                {
                    success = false;
                }
            }
        }

        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            _busyIndicator.IsBusy = false;
            if (success)
            {
                dgSubastas.ItemsSource = subastas;
                tbPaginacion.Visibility = Visibility.Visible;
                UpdatePaginationControls();
            }
            else
            {
                dgSubastas.ItemsSource = null;
                Xceed.Wpf.Toolkit.MessageBox.Show("No se ha podido realizar la búsqueda",
                    "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void UpdatePaginationControls()
        {
            String iniString = "0";
            String deString = "";

            if (numSubastas > 0)
                iniString = (pagenum * pageSize + 1).ToString();

            btAnterior.IsEnabled = pagenum == 0 ? false : true;

            if (pagenum + 1 >= numSubastas / (float)pageSize)
            {
                btSiguiente.IsEnabled = false;
                deString = numSubastas.ToString();
            }
            else
            {
                btSiguiente.IsEnabled = true;
                deString = ((pagenum + 1) * pageSize).ToString();
            }

            lbPagina.Content = iniString + " - " + deString + " de " + numSubastas;
        }

        private void btAnterior_Click(object sender, RoutedEventArgs e)
        {
            if (!worker.IsBusy)
            {
                _busyIndicator.IsBusy = true;
                pagenum--;
                worker.RunWorkerAsync();
            }
        }

        private void btSiguiente_Click(object sender, RoutedEventArgs e)
        {
            if (!worker.IsBusy)
            {
                _busyIndicator.IsBusy = true;
                pagenum++;
                worker.RunWorkerAsync();
            }
        }

        private void btSiguiente_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            IntPtr b;
            BitmapSource bs;

            if (imgBtSiguiente != null)
            {
                b = Convert.ToBoolean(e.NewValue) ? Properties.Resources.Right_24.GetHbitmap() : Properties.Resources.RightBW_24.GetHbitmap();
                bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(b, IntPtr.Zero, Int32Rect.Empty,
                  System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                this.imgBtSiguiente.Source = bs;
            }
        }

        private void btAnterior_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            IntPtr b;
            BitmapSource bs;

            if (imgBtAnterior != null)
            {
                b = Convert.ToBoolean(e.NewValue) ? Properties.Resources.Left_24.GetHbitmap() : Properties.Resources.LeftBW_24.GetHbitmap();
                bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(b, IntPtr.Zero, Int32Rect.Empty,
                  System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                this.imgBtAnterior.Source = bs;
            }
        }

        private void btNuevo_Click(object sender, RoutedEventArgs e)
        {
            DocumentContent doc = FindDocumentContent(typeof(ucSubastaData));

            if (doc == null)
                ShowPageInParentDock<ucSubastaData>();
            else
                Xceed.Wpf.Toolkit.MessageBox.Show("Ya hay abierta una ventana de creación o edición de subastas. Ciérrela antes de abrir otra.",
                    "Error", MessageBoxButton.OK, MessageBoxImage.Error);
        }

        private DocumentContent FindDocumentContent(Type t)
        {
            DockingManager manager;

            manager = ((AvalonDock.DocumentContent)this.Parent).Manager;
            // Buscamos si hay abierta una instancia del documento a abrir
            foreach (AvalonDock.DocumentContent doc in manager.Documents)
            {
                if (doc.Content.GetType() == t)
                    return doc;
            }
            return null;
        }

        private void ShowPageInParentDock<T>(EntityObject obj = null) where T : UserControl
        {
            DependencyObject padre = this.Parent;
            UserControl control;

            if (typeof(T) == typeof(ucSubastaData))
            {
                control = obj != null ? new ucSubastaData((Subasta)obj) : new ucSubastaData();
                ((ucSubastaData)control).SubastaCAD = subastaCAD;
                OpenNewDocument(control);
            }
            else if (typeof(T) == typeof(ucSubastaPujaData))
            {
                control = obj != null ? new ucSubastaPujaData((Subasta)obj) : new ucSubastaPujaData();
                ((ucSubastaPujaData)control).SubastaCAD = subastaCAD;
                OpenNewDocument(control);
            }
        }

        private void OpenNewDocument(UserControl c)
        {
            DependencyObject padre;

            try
            {
                padre = this.Parent;
                if (padre is AvalonDock.DocumentContent)
                {
                    padre = ((AvalonDock.DocumentContent)padre).Manager;
                    if (padre is AvalonDock.DockingManager)
                    {
                        padre = ((AvalonDock.DockingManager)padre).Parent;
                        if (padre is Grid)
                        {
                            padre = ((Grid)padre).Parent;

                            if (padre is UserWindow)
                            {
                                if (c is ucSubastaData)
                                    ((UserWindow)padre).ShowPage<ucSubastaData>((ucSubastaData)c);
                                else if (c is ucSubastaPujaData)
                                    ((UserWindow)padre).ShowPage<ucSubastaPujaData>((ucSubastaPujaData)c);
                            }
                            else
                                throw new ErrorOpeningNewDocumentException("No se puede abrir la nueva ventana");
                        }
                        else
                            throw new ErrorOpeningNewDocumentException("No se puede abrir la nueva ventana");
                    }
                    else
                        throw new ErrorOpeningNewDocumentException("No se puede abrir la nueva ventana");
                }
                else
                    throw new ErrorOpeningNewDocumentException("No se puede abrir la nueva ventana");
            }
            catch (ErrorOpeningNewDocumentException ex)
            {
                Xceed.Wpf.Toolkit.MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
        }

        public void ActualizarDataGrid()
        {
            if (!worker.IsBusy)
            {
                _busyIndicator.IsBusy = true;
                subastaCAD = new SubastaCAD();
                subastaCAD.SetQueryFilters(null);
                dgSubastas.ItemsSource = null;
                numSubastas = -1;
                worker.RunWorkerAsync();
            }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (!loaded)
            {
                loaded = true;
                if (!worker.IsBusy)
                {
                    _busyIndicator.IsBusy = true;
                    subastaCAD = new SubastaCAD();
                    numSubastas = -1;
                    pagenum = 0;

                    if (!workerPermisos.IsBusy)
                        workerPermisos.RunWorkerAsync();
                    System.Threading.Thread.Sleep(100);
                    worker.RunWorkerAsync();
                }
            }
        }

        private void cbListadoSubastas_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SubastaFilter filtro = null;
            List<SubastaFilter> filtros;

            if (cbListadoSubastas.SelectedIndex != -1)
            {
                
                filtros = new List<SubastaFilter>();
                switch (cbListadoSubastas.SelectedIndex)
                {
                    case 0:
                        filtro = new SubastaFilter(@"it IS NOT OF (ModeloGaleriaNET.SubastaDeOtro) and EXISTS (select shs.estado from subastashaveestadossubasta as " +
                        @"shs where it.id = shs.subasta and shs.fechafin is null and (shs.estado = 5 or shs.estado = 6))", null);
                        break;
                    case 1:
                        filtro = new SubastaFilter(@"it IS NOT OF (ModeloGaleriaNET.SubastaDeOtro) and EXISTS (select shs.estado from subastashaveestadossubasta as " +
                        @"shs where it.id = shs.subasta and shs.fechafin is null and shs.estado = 1)", null);
                        break;
                    case 2:
                        filtro = new SubastaFilter(@"it IS NOT OF (ModeloGaleriaNET.SubastaDeOtro) and EXISTS (select shs.estado from subastashaveestadossubasta as " +
                        @"shs where it.id = shs.subasta and shs.fechafin is null and (shs.estado = 2 or shs.estado = 3))", null);
                        break;
                    case 3:
                        filtro = new SubastaFilter("it IS OF (ModeloGaleriaNET.SubastaDeOtro)", null);
                        break;
                }
                
                if (!worker.IsBusy)
                {
                    filtros.Add(filtro);
                    subastaCAD.SetQueryFilters(filtros);
                    _busyIndicator.IsBusy = true;
                    numSubastas = -1;
                    pagenum = 0;
                    worker.RunWorkerAsync();
                }
            }
        }

        private void btLimpiar_Click(object sender, RoutedEventArgs e)
        {
            if (!worker.IsBusy)
            {
                _busyIndicator.IsBusy = true;
                subastaCAD.SetQueryFilters(null);
                numSubastas = -1;
                pagenum = 0;
                worker.RunWorkerAsync();
            }
        }

        private void btBuscar_Click(object sender, RoutedEventArgs e)
        {
            SubastaFilterWindow busqueda;

            busqueda = new SubastaFilterWindow();
            busqueda.ShowDialog();

            if (busqueda.Success) // Realizar búsqueda
            {
                if (!worker.IsBusy)
                {
                    _busyIndicator.IsBusy = true;
                    subastaCAD.SetQueryFilters(busqueda.Filters);
                    dgSubastas.ItemsSource = null;
                    dgSubastas.Items.Clear();
                    numSubastas = -1;
                    pagenum = 0;
                    worker.RunWorkerAsync();
                }
            }
        }

        private void dgSubastas_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            DataGrid grid;
            DataGridRow dgr;
            DocumentContent doc;
            
            if (sender != null)
            {
                grid = sender as DataGrid;
                if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1)
                {
                    dgr = grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem) as DataGridRow;
                    doc = FindDocumentContent(typeof(ucSubastaPujaData));

                    if (doc == null)
                        ShowPageInParentDock<ucSubastaPujaData>((EntityObject)(dgr.Item));
                    else
                        Xceed.Wpf.Toolkit.MessageBox.Show("Ya hay abierta una ventana de datos de subasta.\nCiérrela antes de abrir otra",
                            "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
    }
}
